package com.lzs.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzs.entity.Dict;
import com.lzs.system.mapper.DictMapper;
import com.lzs.system.service.DictService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzs.util.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 基础字典 服务实现类
 * </p>
 *
 * @author ymw
 * @since 2020-12-09
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    private DictMapper dictMapper;

    /**
     * 字典分页查询
     * @param page
     * @param limit
     * @param dict
     * @return
     */
    @Override
    public Page<Dict> selectAllDictPage(Integer page, Integer limit, Dict dict) {
        Page<Dict> dictPage=new Page<>(page,limit);
        Long dictTypeId = dict.getDictTypeId();
        String name = dict.getName();
        QueryWrapper<Dict> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("dict_type_id",dictTypeId);
        if (StringUtils.isNotEmpty(name)){
            queryWrapper.like("name",name);
        }
        dictMapper.selectPage(dictPage, queryWrapper);
        return dictPage;
    }

    /**
     * 字典新增修改
     * @param dict
     * @return
     */
    @Override
    public R insertOrUpdateDict(Dict dict) {
        if (dict.getDictId()!=null){
            dict.setUpdateTime(new Date());
            int i = dictMapper.updateById(dict);
            if (i>0){
                return R.ok().message("修改成功");
            }
            return R.ok().message("修改失败");
        }else {
            dict.setCreateTime(new Date());
            int i = dictMapper.insert(dict);
            if (i>0){
                return R.ok().message("新增成功");
            }
            return R.ok().message("新增失败");
        }
    }

    /**
     * 修改时根据ID回显内容
     * @param dictId
     * @return
     */
    @Override
    public R findByDictId(Long dictId) {
        Dict dict = dictMapper.selectById(dictId);
        return R.ok().data("dict",dict);
    }
}
